

import { getKnowLedgeId, getKnowLedgeKid, getKnowledgeList } from '@/services';
import { IKnowledgeItem, KnowledgeId } from '@/types';
import { Effect, Reducer } from 'umi';

// 定义模块内部状态的类型
export interface KnowledgeModelState {
  knowledgs: IKnowledgeItem[];
  knowledsLength:number;
  knowledgsId: Partial<KnowledgeId>;
}

// 定义模块的类型
export interface KnowledgeModelType {
  namespace: 'knowledge';
  state: KnowledgeModelState;
  effects: {
    getKnowLedgeList: Effect;
    getKnowLedgeId: Effect;
    getKnowLedgeKid:Effect
  };
  reducers: {
    save: Reducer<KnowledgeModelState>;
  };
}

const KnowledgeModel: KnowledgeModelType = {
  // 模块命名空间
  namespace: 'knowledge',

  // 模块内部状态
  state: {
    knowledgs: [],
    knowledsLength:0,
    knowledgsId:JSON.parse(localStorage.getItem('knowledgsId')! ) || {}
    
  },


  effects: {
    // 知识小册
    *getKnowLedgeList({ payload }, { call, put }) {
      const result = yield call(getKnowledgeList,payload);
    //   localStorage.setItem('knowledgs', result.data[0]);
      if (result.statusCode === 200) {
        yield put({
          type: 'save',
          payload: {
            knowledgs: result.data[0],
            knowledsLength: result.data[1],
          },
        });
      }
    },
    // 知识小册得详情
    *getKnowLedgeId({ payload }, { call, put }) {
      const result = yield call(getKnowLedgeId, payload);
      localStorage.setItem('knowledgsId', JSON.stringify(result.data))
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            knowledgsId: result.data,
          },
        });
      }
    },
    
  },

  // 同步修改
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default KnowledgeModel;
